<template>
  <uni-file-picker limit="9"
  	@select="select"  
  	@delete="deleteFn" 
  	:value="fileList" 
  title="最多选择9张图片"></uni-file-picker>
</template>
<script setup>
	import {ref,watch} from 'vue'
	const emit = defineEmits()

	const props = defineProps({
		modelValue: {
			type: Array,
			default: ()=>[]
		}
	})
	
	

	const fileList= ref([])
	
	watch(() => props.modelValue, val => {
		fileList.value = val
	},{ deep: true, immediate: true });
	const select =(e) =>{
		
		let arr = e.tempFilePaths.map((item,index)=>{
			return {
				path:item,
				url:item
			}
		// 	return getBase64(item,index)
		})
		fileList.value = [...fileList.value,...arr]
		
		// uni.setStorageSync('imgData',fileList.value)
		emit('update:modelValue', fileList.value)
		
		// let arr = e.tempFilePaths.map((item,index)=>{
		// 	return getBase64(item,index)
		// })
		
		// Promise.all(arr).then(res=>{
		// 	console.log(res,'结果');
		// 	fileList.value = [...fileList.value,...res]
		// 	emit('update:modelValue', fileList.value)
		// })
	}
	
	
	const getBase64 = (filePath,index) =>{
		return new Promise((resolve,reject)=>{
			let isH5 = process.env.VUE_APP_PLATFORM === 'h5'
			let isAndroid = !isH5 && uni.getSystemInfoSync().platform === 'android'
			if(isH5){
				const xhr = new XMLHttpRequest()
				xhr.open('GET', filePath, true)
				xhr.responseType = 'blob'
				xhr.onload = () => {
					const reader = new FileReader()
					reader.onloadend = (e) => {
						console.log(e,reader);
						resolve({
							url:reader.result,
							index
						})
					}
					reader.onerror = reject
					reader.readAsDataURL(xhr.response)
				}
				xhr.onerror = reject
				xhr.send()
			}
			
		})
		
		
		
	}
	
	const deleteFn =({index}) =>{
		console.log(fileList.value);
		fileList.value.splice(index,1)
		emit('update:modelValue', fileList.value)
		
	}
</script>


<style>

</style>